package com.dream.common.enums;

import com.dream.common.constans.RedisKeysDefine;
import com.dream.common.utils.JsonUtils;
import com.dream.common.utils.payutils.bean.MessageBeanOld;
import com.dream.dto.request.UploadFriendListRequest;
import com.dream.dto.request.UploadGroupListRequest;
import com.dream.dto.socket.GroupMemberSocketBean;
import com.dream.dto.socket.SocketBean;
import com.dream.entity.FriendMapping;
import com.dream.entity.GroupMember;
import com.dream.mapper.GroupMemberMapper;
import com.dream.service.basic.BaseServiceHelper;
import com.dream.net.socket.base.BaseSocketController;
import com.github.binarywang.java.emoji.EmojiConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;


public enum ReportedDataActionEnum {
    /**
     * 上报数据操作类
     */

    IM_MSG(1, "消息发送---{}") {
        @Override
        public void resolve(SocketBean socketBean) {
            logger.info(description, socketBean);
            MessageBeanOld messageBean = JsonUtils.parseObject(socketBean.data, MessageBeanOld.class);
            assert messageBean != null;

            if (messageBean.atList != null && messageBean.atList.size() > 0) {
                messageBean.sendMsg = messageBean.sendMsg.replace("@", "");
                if (messageBean.groupName != null && !"".equals(messageBean.groupName)) {
                    messageBean.groupName = EmojiConverter.getInstance().toUnicode(messageBean.groupName);
                }
                if (messageBean.sendMessageUserName != null && !"".equals(messageBean.sendMessageUserName)) {
                    messageBean.sendMessageUserName = EmojiConverter.getInstance().toUnicode(messageBean.sendMessageUserName);
                }
                for (MessageBeanOld.AtUserInfo atUserInfo : messageBean.atList) {
                    messageBean.sendMsg = messageBean.sendMsg.replace(atUserInfo.atUserName + " ", "");
                    messageBean.sendMsg = messageBean.sendMsg.replace("#" + atUserInfo.atUserId + " ", "");
                }
            }

            String userName = messageBean.userName;
            String msg = JsonUtils.toJSONString(socketBean);
            //存储查我，自定义命令消息
            BaseServiceHelper.getAsyncInvokeService().msgUnityWrite(userName, socketBean.data);
            BaseServiceHelper.getConsoleWebSocket().sendMessageToUser(userName, msg);

            //自定义消息处理
            CustomMsgEnum customMsgEnum = CustomMsgEnum.getEnumByTag(messageBean.sendMsg);
            if (customMsgEnum != null) {
                //存储自定义响应的消息
                customMsgEnum.resolve(messageBean);
            }
        }
    },

    FRIEND_LIST(3, "APP获取好友列表{}") {
        @Override
        public void resolve(SocketBean socketBean) {
            logger.info(description, socketBean);
            UploadFriendListRequest uploadFriendList = JsonUtils.parseObject(socketBean.data, UploadFriendListRequest.class);
            assert uploadFriendList != null;
            if (uploadFriendList.friendListInfo.size() > 0) {
                for (FriendMapping friendMapping : uploadFriendList.friendListInfo) {
                    friendMapping.friendHeadImg = friendMapping.friendHeadImg.replace("\\u003d", "");
                    friendMapping.userName = uploadFriendList.userName;
                    if (friendMapping.friendName != null && !"".equals(friendMapping.friendName)) {
                        friendMapping.friendName = EmojiConverter.getInstance().toUnicode(friendMapping.friendName);
                    }
                }
                BaseServiceHelper.getFriendManagerMapper().uploadFriendList(uploadFriendList.friendListInfo);
            }
        }
    },

    GROUP_LIST(4, "APP获取群列表{}") {
        @Override
        public void resolve(SocketBean socketBean) {
            logger.info(description, socketBean);
            UploadGroupListRequest uploadGroupList = JsonUtils.parseObject(socketBean.data, UploadGroupListRequest.class);
            assert uploadGroupList != null;
            if (!CollectionUtils.isEmpty(uploadGroupList.groupListInfo)) {
                uploadGroupList.groupListInfo.forEach(e -> {
                    e.groupHeadImg = e.groupHeadImg.replace("\\u003d", "");
                    if (e.groupName != null && !"".equals(e.groupName)) {
                        e.groupName = EmojiConverter.getInstance().toUnicode(e.groupName);
                    }
                    if (StringUtils.isEmpty(e.groupName)) {
                        e.groupName = "未命名群聊";
                    }

                    if (StringUtils.isEmpty(e.userName)) {
                        e.userName = uploadGroupList.userName;
                    }
                });

                //同步数据库
                BaseServiceHelper.getGroupInfoMapper().replaceGroupInfo(uploadGroupList.groupListInfo);
            }
        }
    },


    GROUP_MEMBER_LIST(5, "APP上报群成员列表{}") {
        @Override
        public void resolve(SocketBean socketBean) {
            logger.info(description, socketBean);
            GroupMemberSocketBean groupMemberSocketBean = JsonUtils.parseObject(socketBean.data, GroupMemberSocketBean.class);
            assert groupMemberSocketBean != null;
            if (!CollectionUtils.isEmpty(groupMemberSocketBean.friendListInfo)) {
                //查询出这些成员所有所在群
                GroupMemberMapper memberMapper = BaseServiceHelper.getGroupMemberMapper();
                Example queryExample = new Example(GroupMember.class);
                queryExample.or().andEqualTo("userName", groupMemberSocketBean.userName);
                List<GroupMember> groupMemberList = memberMapper.selectByExample(queryExample);

                //可能存在上传少群成员情况,需要先delete
                queryExample.clear();
                queryExample.or().andEqualTo("userName", groupMemberSocketBean.userName);
                memberMapper.deleteByExample(queryExample);

                //转为map，进行groupId比对，如果一样的，进行角色赋值
                groupMemberSocketBean.friendListInfo.parallelStream().forEach(socketItem -> {
                    socketItem.groupId = groupMemberSocketBean.groupId;
                    socketItem.userName = groupMemberSocketBean.userName;
                    if (socketItem.groupName != null && !"".equals(socketItem.groupName)) {
                        socketItem.groupName = EmojiConverter.getInstance().toUnicode(socketItem.groupName);
                    }
                    if (socketItem.friendName != null && !"".equals(socketItem.friendName)) {
                        socketItem.friendName = EmojiConverter.getInstance().toUnicode(socketItem.friendName);
                    }
                    //之前所在群
                    groupMemberList.parallelStream().forEach(dbItem -> {
                        if (Objects.equals(dbItem.friendId, socketItem.friendId)) {
                            //app不能设置枪包手和托,只能管理台控制,所以赋值db数据
                            if (socketItem.isTouchPack == null || socketItem.isTouchPack == 0) {
                                socketItem.isTouchPack = dbItem.isTouchPack;
                            }
                            if (socketItem.isInsideUser == null || socketItem.isInsideUser == 0) {
                                socketItem.isInsideUser = dbItem.isInsideUser;
                            }
                        }
                        //黑名単和管理员，如果之前相同群有这二个角色不继承
                        //socketItem.isManager = socketItem.isManager != null && socketItem.isManager != 0?  socketItem.isManager : dbe.isManager;
                        //socketItem.isBlackList = socketItem.isBlackList != null && socketItem.isBlackList != 0 ? socketItem.isBlackList : dbe.isBlackList;
                    });

                    if (StringUtils.isEmpty(socketItem.groupName)) {
                        socketItem.groupName = "未命名群聊";
                    }
                });
                //同步数据库
                memberMapper.insertList(groupMemberSocketBean.friendListInfo);
                //删除这个账号下面的群成员角色缓存
                BaseServiceHelper.getRedisCacheService().del(RedisKeysDefine.USER_ROLES.concat(groupMemberSocketBean.userName));
                //通知web
                socketBean.data = JsonUtils.toJSONString(groupMemberSocketBean.friendListInfo);
                BaseServiceHelper.getConsoleWebSocket().sendMessageToUser(groupMemberSocketBean.userName, JsonUtils.toJSONString(socketBean));
            }
        }
    },

    ROLE_SETTING(6, "APP设置管理员和黑名単角色{}--") {
        @Override
        public void resolve(SocketBean socketBean) {
            logger.info(description, socketBean);
            GroupMember memberSocketRole = JsonUtils.parseObject(socketBean.data, GroupMember.class);
            assert memberSocketRole != null;
            Example example = new Example(GroupMember.class);
            example.or().andEqualTo("userName", memberSocketRole.userName)
                    .andEqualTo("friendId", memberSocketRole.friendId);
            BaseServiceHelper.getGroupMemberMapper().updateByExampleSelective(memberSocketRole, example);
        }
    },

    KICK_OUT(7, "APP踢出群成员{}--") {
        @Override
        public void resolve(SocketBean socketBean) {
            logger.info(description, socketBean);
            GroupMember removeMemberSocket = JsonUtils.parseObject(socketBean.data, GroupMember.class);
            assert removeMemberSocket != null;
            Example delExample = new Example(GroupMember.class);
            delExample.or().andEqualTo("friendId", removeMemberSocket.friendId)
                    .andEqualTo("userName", removeMemberSocket.userName);
            BaseServiceHelper.getGroupMemberMapper().deleteByExample(delExample);
        }
    },
    ADD_MEMBER(8, "APP加入群成员{}--") {
        @Override
        public void resolve(SocketBean socketBean) {
            logger.info(description, socketBean.data);
            GroupMember addMemberSocket = JsonUtils.parseObject(socketBean.data, GroupMember.class);
            assert addMemberSocket != null;
            if (addMemberSocket.groupName != null && !"".equals(addMemberSocket.groupName)) {
                addMemberSocket.groupName = EmojiConverter.getInstance().toUnicode(addMemberSocket.groupName);
            }
            if (addMemberSocket.friendName != null && !"".equals(addMemberSocket.friendName)) {
                addMemberSocket.friendName = EmojiConverter.getInstance().toUnicode(addMemberSocket.friendName);
            }
            BaseServiceHelper.getGroupMemberMapper().insert(addMemberSocket);
        }
    };


    public int command;

    public String description;


    ReportedDataActionEnum(int command, String description) {
        this.command = command;
        this.description = description;
    }


    public void resolve(SocketBean data) {
        System.out.println("无匹配command----");
    }

    public static ReportedDataActionEnum getEnumByCode(int code) {
        for (ReportedDataActionEnum operationContent : values()) {
            if (operationContent.command == code) {
                return operationContent;
            }
        }
        return null;
    }


    private static Logger logger = LoggerFactory.getLogger(BaseSocketController.class);

}
